<script lang="tsx">
import { defineComponent, resolveComponent, computed, unref, h } from 'vue';
import type { FormSchema } from './form-dialog';
import { PropType } from 'vue';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import { isString, isArray, isFunction, isBoolean } from '@/utils/is';

export default defineComponent({
  name: 'FormItem',
  components: {
    CDosageAndUnit
  },
  props: {
    schema: {
      type: Object as PropType<FormSchema>,
      default: () => ({})
    },
    formModel: {
      // eslint-disable-next-line no-undef
      type: Object as PropType<Recordable<any>>,
      default: () => ({})
    }
  },
  setup(props) {
    const getValues = computed(() => {
      const { formModel } = props;
      return {
        values: {
          ...formModel
        }
      };
    });

    return () => {
      const { field, fields, component, componentProps, options } = props.schema;

      const values = unref(getValues);
      console.log('values.values[field]', values.values[field]);

      const isDosageComponent = component === 'CDosageAndUnit' && isArray(fields);

      const dosageComponent = isArray(fields) ? (
        <CDosageAndUnit
          dosage={values.values[field]}
          unit={values.values[(fields as string[])[0]]}
        />
      ) : (
        ''
      );

      const optionsList = options?.map(item => <el-option label={item.label} value={item.value} />);
      return isDosageComponent
        ? dosageComponent
        : h(
            resolveComponent(component),
            {
              ...componentProps,
              modelValue: values.values[field]
            },
            () => optionsList
          );
    };
  }
});
</script>

<style scoped></style>
